<?php

class myActions extends sfActions
{
    public function preExecute()
    {
        $this->getUser()->setAuthenticated('1');

        // pass a reference to the current action to the view
        $this->_action = $this;

        $this->_moduleName = $this->getModuleName();
        $this->_actionName = $this->getActionName();
    }

    protected function sendJson($data)
    {
        $this->getResponse()->setHttpHeader('Content-type','application/json');
        $this->setLayout(false);
        $this->renderText(json_encode($data));
    }

    protected function setResponseType($value)
    {
        $this->getResponse()->setHttpHeader('Response-Type', $value);
    }

    /**
     * Trimite catre client valorile specificate
     *
     * @param mixed $data
     * @return int
     */
    public function sendData($data)
    {
        $this->setResponseType('data');
        $this->sendJson($data);
    }

    /**
     * Erorile pot fi globale sau specifice unui camp dintr-un formular
     *
     * @param mixed $error
     * @param bool $global
     */
    public function sendError($error, $global = false)
    {
        if ($global)
        {
            $error = array('global' => $error);
        }

        $this->setResponseType('validation-errors');
        $this->sendJson($error);
    }

    /**
     * Populeaza raspunsul cu continut HTML si, optional, alte valori
     *
     * @param string $html
     * @param mixed $data
     * @return int
     */
    public function sendHtml($html)
    {
        $this->renderText($html);
    }

    public function sendResponse($operation, $view)
    {
        if ($operation === true)
        {
            $this->sendHtml($this->getComponent($view[0], $view[1], (array) $view[2]));
        }
        else
        {
            $this->sendError($operation);
        }
    }

    /**
     * Proceseaza si salveaza datele dintr-un formular
     *
     * @param sfWebRequest $request
     * @param sfFormObject $form
     * @param string $componentName
     * @param array $componentArguments
     * @return int
     */
    public function formRequest(sfWebRequest $request, BaseFormPropel $form, $componentName = null, array $componentArguments = array())
    {
        if (!$form->bindAndSave($request))
        {
            $errors = $form->getErrors();
            $data = $form->getResponseData();
            if ($data)
            {
                $errors += $data;
            }

            $this->sendError($errors);
        }
        elseif ($componentName !== null)
        {
            $view = $this->getComponent($this->getModuleName(), $componentName, $componentArguments);
            $data = $form->getResponseData();

            $this->sendHtml($view, $data);
        }
        else
        {
            // get response data as an array
            $data['data'] = $form->getResponseData();
            $data['success'] = 1;

            $this->sendData($data);
        }

        return sfView::NONE;
    }

}